/*

Script: List.js
	Creates a generic list

Copyright:
	Copyright (c) 2010 Chris Doty, <http://polaropposite.com/>.

License:
	MIT-style license.

*/

MUI.files[MUI.path.plugins + 'mochaList/List.js'] = 'loaded';

MUI.List = new Class({
    Implements: [Events, Options],

    options: {
        id:                 ''          // id of the primary element, and id os control that is registered with mocha
       ,instanceName:		''			// 实例的名称
       ,container:          null        // the parent control in the document to add the control to
       ,createOnInit:       true        // true to add tree to container when control is initialized
       ,cssClass:           'list'      // the primary css tag

       ,showCommand:        true        // turns row commands on or off
       ,commands:           $A([])      // commands to be used
       ,iconPath:           ''          // parent path to command icons

       ,dataURL:			null		// 从哪个地址取数据
       ,dataURLParams:		null		// 传递给dataURL以参数

       ,pageOverView:		null		// 翻页参数
       ,pageCurrentPage:	0			//当前页
       ,items:              $A([])      // the array list of nodes
       ,columns:            $A([])      // the list of columns to be used
       ,cbName :			'ids'		//CHECKBOX的名字
       ,showCheckBox:       false       // true to show checkBoxes
       ,saveCheck:			false		//为TRUE的时候,勾选的checkbox值存放在curCheckIds
       ,curCheckIds:        new Array() 
       ,navigateURL:        ''          // the base url to navigate from
       ,canSelect:          true        // can the user select a row by clicking it
       ,value:              ''          // the currently selected item's value
       ,selectedItem:       null        // the currently selected item

       ,onItemCommand:      $empty      // event: when a command is performed
       ,onItemSelected:     $empty      // event: when a node is selected
       ,onItemChecked:      $empty      // event: when a node is selected
       ,onItemColumnBound:  $empty      // event: when a node's column is bound to the data
    },

    initialize: function(options) {
        this.setOptions(options);

        // make sure this controls has an ID
        var id=this.options.id;
        if(!id) { id='list' + (++MUI.IDCount); this.options.id=id; }
        // create sub items if available
        if(this.options.createOnInit && this.options.items.length>0) this.toDOM();
        else if($(id)) this.fromHTML(id);

        MUI.set(id,this);  
        this.options.curCheckIds.empty(); 
    },
    
    //////////////////////////////////////////////////////////////
   /* getCurCheckIds: function(){
    	 curCheckIds.each(function(item, index){
    		 alert(index + "=" + item);

    	 });
    },
    */
    //新增方法checkAll,反选所有
    checkAll: function(){
    	var self = this;
    	var o = self.options;
    	var m = document.getElementsByName(o.cbName); 
    	var mall = $('checkids'+o.cbName); 
    	 var l = m.length;
         for ( var i=0; i< l; i++)
         {
             //m[i].checked == true 
             //    ? m[i].checked = false
             //    : m[i].checked = true;
             if(mall.checked){
        		 m[i].checked = true;
        		 if ( ! o.curCheckIds.contains(m[i].value) )  o.curCheckIds.include(m[i].value); 
        	}else{
        		 m[i].checked = false;
        		 if ( o.curCheckIds.contains(m[i].value) ) o.curCheckIds.erase(m[i].value); 
        	}
        	/*
        	 if(m[i].checked){
        		 m[i].checked = false;
        	 if ( o.curCheckIds.contains(m[i].value) ) o.curCheckIds.erase(m[i].value); 
        	 }else{
        		 m[i].checked = true;
        		 if ( ! o.curCheckIds.contains(m[i].value) )  o.curCheckIds.include(m[i].value); 
        	 }
        	 */
         }

         
		//	myArray.each(function(item, index){
    	//	if (item){
    	//		if (item.checked){item.checked = false;}else{item.checked = true;}
    	//		}
		//	});
    },
    //取消所有选中的CHECKBOX
    cancelAll: function(){
    	var self = this;
    	var o = self.options;
    	var m = document.getElementsByName(o.cbName);
    	 
    	 var l = m.length;
         for ( var i=0; i< l; i++)
         {
        	 m[i].checked = false;
         }
    },
    //返回当前页面选中多少项CHECKBOX(checkbox的数量)
    checkIds: function(){
    	var self = this;
    	var o = self.options;
    	/* var myArray = $(o.id).getElements('.checkallclass'); 
		var itemcount =0;
		myArray.each(function(item, index){
    		if (item){
    			if (item.checked){itemcount++;}
    			}
			});
			*/
    	var itemcount =0;
    	var m = document.getElementsByName(o.cbName); 
   	 	var l = m.length;
        for ( var i=0; i< l; i++)
        {
            if(m[i].checked){itemcount++;}
        }
		return itemcount;
		
    },
    //返回选中的所有CHECKBOX对象(注意是对象,当前页多项),如果saveCheck=true,更新curCheckIds
    findIds: function(){
    	var self = this;
    	var o = self.options;
    	//var myArray = $(o.id).getElements('.checkallclass'); 
    	var retArray=new Array() ;
    	var i =0;
    	var m = document.getElementsByName(o.cbName); 
   	 	var l = m.length;
        for ( var j=0; j< l; j++)
        {
            if(m[j].checked){
            	retArray[i]=m[j];
            	i++;
            	if ( o.saveCheck && ! o.curCheckIds.contains(m[j].value) )  
            		o.curCheckIds.include(m[j].value); 
            }else{
            	if ( o.saveCheck &&  o.curCheckIds.contains(m[j].value) )  
            		o.curCheckIds.erase(m[j].value); 
            }
                
        }
    //	var retArray=new Array() ;
    //	var i =0;
	//	myArray.each(function(item, index){
    //		if (item){
    //			if (item.checked){retArray[i]=item; i++;}
    //			}
	//		});
		return retArray;
    },
    //返回当前页面选中的CHECKBOX对象(一项)
    findFirstIds: function(){
    	var self = this;
    	var retArray = self.findIds();
    	if(null == retArray)
    		return null;
    	return retArray[0];
    },
    
    //把数组(存放的是checkbox)的值转成字符串,以,分隔
    arrCbToStr : function(arr){
		var ret ="";
		if(null != arr && arr.length>0){ 
			arr.each(function(item, index){
	    		if (ret==""){
	    			ret = item.value;
	    		}else{
	    			ret = ret + ',' + item.value;
	    		}
			});	
		}
		return ret;
	},
	
	getcurCheckIds: function(){
		 var self = this;
	     var o = self.options;
    	return  o.curCheckIds;
    },
    
    //清空curCheckIds(一般是翻页,保存几页的勾选项)
    clearCheckIds : function(){
    	var self = this;
    	var o = self.options;
    	o.curCheckIds.empty(); 
    },
    
    setColumns: function(columns){
    	var self = this;
    	var o = self.options;
    	o.columns = columns;
    },
    
    setDataURLParams: function(dataURLParams){
    	var self = this;
    	var o = self.options;
    	o.dataURLParams = dataURLParams;
    },
    
    toDOM: function(containerEl) {
        var self = this;
        var o = self.options;
		var container=$(containerEl ? containerEl : o.container);
		if (container) { container.empty(); }
		//var myFx = new Fx.Scroll(container).toElement(container);
		var myFx = new Fx.Scroll(window).toTop();
        // see if we need build columns automagically
        // 组装字段名
        if(o.columns==null || o.columns.length==0) {
            var ii=0;
            o.columns=[];
            var first=$H(o.items[0]);
            first.each(function(value,key) {
                var h={'text':key,'name':key};
                if($type(value)=='boolean') h.type='checkbox';
                if(ii==0) h['value'] = key;
                o.columns.push(h);
                i++;
            });
        }

        // build control's wrapper div
        var div = $(self.id);
        var isNew = false;
        if (!div) {                     // check to see if it is already on DOM
            div = new Element('div');
            div.id = o.id;
            isNew = true;
        }
        //div.empty();//清空子元素
        if (o.cssClass) div.set('class',o.cssClass);
        self.element = div;

        //-------------------------
        new Element('a',{'name':'top','id':'top'}).inject(div);
        // build table
        var table = div.getElement('table');
        if(!table) { table=new Element('table',{'cellSpacing':0,'cellPadding':0,'styles':{'width':'100%'}}).inject(div); }

        // build column headers
        var tbody = table.getElement('tbody');
        var i,tr;
        if(!tbody) {
            tbody=new Element('tbody').inject(table);

            tr = new Element('tr',{'class':'head'}).inject(tbody);
            var cl = o.columns;
            for (i = 0; i < cl.length; i++) {
            	var td = new Element('td',{'valign':'bottom'}).inject(tr);
				if (i == 0) { 
                	td.addClass('First'); 
                	//===================================================================
                	//以下为自添加代码
                	if (o.showCheckBox) {
                		//添加一个check all的checkbox
                    	var _cb = new Element('input', { 'type': 'checkbox', 'name': 'checkids'+o.cbName, 'id': 'checkids'+o.cbName}).inject(td,'top');
                    	_cb.addEvent('click', function(event) { event.stopPropagation(); self.checkAll(); });
                    	//td.appendChild(document.createTextNode(' 反选'));//在checkbox与文字间加个空格
                	}
                }
                if(!o.showCheckBox || i!=0) td.appendChild(document.createTextNode(cl[i].text.replace(new RegExp(/\|/g), '<br/>')));
                if(cl[i].align) { td.set('align',cl[i].align); }
            }
            
            // add command headers if they have commands
            if (o.commands && o.commands.length > 0) {
                tr.appendChild(new Element('td',{'class':'head','html':'&nbsp;'}));
            }
        }

        // determine currently selected item
        var value = o.value;

        // build rows
        var items = o.items;
        if(items) {
            for (i = 0; i < items.length; i++) {
                // build the row
                var item=items[i];
                self.buildItem(item,tbody);
                tr = item._element;

                // select row if it needs to selected
                /*
                var sel = (item.value == value && value!='');
                item.selected = sel;
                if (sel) tr.addClass('C');
                else if(i % 2) tr.addClass('alt');
                */
                if(i % 2) tr.addClass('alt');
            }
        }
        // build pageOverView
        var pageOverView = o.pageOverView;
        if (pageOverView && pageOverView.tpage>1) { self.buildPageOverView(pageOverView , tbody); }
       //-------------------------

        if(!isNew) return this;
		
        // add control to document
        window.addEvent('domready', function() {
            var container=$(containerEl ? containerEl : o.container);
            if (container) { 
            	container.appendChild(div); 
            	/*
            	MUI.updateContent({
					'element':  container,
					'content':  div.innerHTML
				});
				*/
            }
            //alert(div.innerHTML);
        });
        
        //var container=$(containerEl ? containerEl : o.container);
        //container.appendChild(div); 
        return self;

    },
    
    buildPageOverView: function(pageOverView , parent){
    	var self = this;
        var o=self.options;
    	//var rid = 'pageOverView';
    	 var id = o.id;
    	var rid = id+'_pageOverView';
    	
    	var tr = $(rid);
        if (!tr) tr = $(new Element('tr', { 'id': rid,'class':'head1' })).inject(parent);
        
        //tr = new Element('tr',{'class':'head'}).inject(tbody);
    	
		var str = "";
		str+= '共'+pageOverView.tcount+'条 '; 
		str+= '第'+pageOverView.cpage+'/'+pageOverView.tpage+'页 '
		str+= pageOverView.maxline+'条/页 ';
		if (pageOverView.cminpage>0){
    		str += '&nbsp;<span onclick=\"'+ o.instanceName +'.findList(1)\" style="cursor:pointer"><b>|</b>&lt;&lt;</span>&nbsp;';
    		str += '&nbsp;<span onclick=\"'+ o.instanceName +'.findList(' + pageOverView.cminpage + ')\" style="cursor:pointer">&lt;&lt;</span>&nbsp;';
    	}
		pageOverView.pagenumber.each(
	    	function(no, index){
				if (pageOverView.cpage==no){
          			str += '&nbsp;<b>'+no+'</b>&nbsp;';
       			}else{ 
          			str += '&nbsp;<span onclick=\"'+ o.instanceName +'.findList(' + no + ');\" style="cursor:pointer"><u><b>'+no+'</b></u></span>&nbsp;';
       			} 
		 	}
		);
		if (pageOverView.cmaxpage>0){
    		str += '&nbsp;<span onclick=\"'+ o.instanceName +'.findList(' + pageOverView.cmaxpage + ')\" style="cursor:pointer">&gt;&gt;</span>&nbsp;';
    		str += '&nbsp;<span onclick=\"'+ o.instanceName +'.findList(' + pageOverView.tpage + ')\" style="cursor:pointer">&gt;&gt;<b>|</b></span>&nbsp;';
    	}
    	str += '<span style="padding: 0"> 跳转到: <input type="text" name="custompage" size="1" style="border: 1px solid #698CC3" onKeyDown="if(event.keyCode==13){ if(!isNaN(this.value) && (this.value != \'\')){ '+ o.instanceName +'.findList(this.value);}else{alert(\'请输入数字!\');this.value=\'\';}}"> 页';
		var td = new Element('td',{'html': str,'valign':'bottom','align':'right','colspan':o.columns.length}).inject(tr);
           
    },

    buildItem: function(item,parent) {
        var self = this;
        var o=self.options;
        var id = o.id;

        var cl = o.columns;
        var value = '' + self._getData(item, cl[0].value);//item[property]
		//alert(cl[0].value);
        if (!value) value = '' + parent.childNodes.length;
        var rid = id + '_' + value.replace(/[\s\.]/g, '_');

        var tr = $(rid);
        if (!tr) tr = $(new Element('tr', { 'id': rid })).inject(parent);
        item._element = tr;
		//item._element.removeClass('C');
        var i,td,tid,img,a;
        for (i = 0; i < cl.length; i++) {
            var col = cl[i];

            tid = rid + '_' + i;
            td = tr.getElementById(tid);

            // create column cell
            if (td) td.empty();
            else { td = new Element('td', { 'id': tid }).inject(tr); }
            if (col.align) { td.set('align', col.align); }
            if (col.cssClass) td.set('class',col.cssClass);

            // create items text node
            var txt;
            if (col.cols){
				var _cols = col.cols;
            	var txtValue = '';
            	var arr = self._getData(item, col.name);
            	var separator = ',';
            	if(col.colsSeparator) separator = col.colsSeparator;
            	arr.each(function(_item, index){
    		 		_cols.each(function(_item1, _index1){
    		 			txtValue +=  _item[_item1]+ " ";
    		 		});
    		 		
    		 		if(index<arr.length-1) txtValue += separator;
    	 		});

    	 	    
    	 		//txt = document.createTextNode(txtValue);
    	 		txt = txtValue;
            }else{
            	//txt = document.createTextNode(self._getData(item, col.name));
            	txt = self._getData(item, col.name);
            }
            //var txt = document.createTextNode(self._getData(item, col.name));
            //alert(txt.data);

            if (i == 0) {//处理第一列
                // special handling of first column
                if (o.showCheckBox) {
                	//修改了checkbox.name
                    var cb = new Element('input', { 'type': 'checkbox', 'name': o.cbName, 'value': self._getData(item, col.name) ,'class':'checkallclass' }).inject(td);
                    td.appendChild(document.createTextNode(' '));//在checkbox与文字间加个空格
                    td.width=20;//修改列宽
                    cb.addEvent('click', function(event) { event.stopPropagation(); self.findIds(); self.fireEvent('itemChecked', [item,self,parent]); });
                } else if (!self.value) td.addEvent('click', function(event) { event.stopPropagation(); });

                // create image if needed
                //该列为图片
                if (col.image) {
                    var cImage = self._getData(item, col.image);
                    cImage.replace(/~/g, o.iconPath);
                    if (cImage) img = new Element('img',{'alt':'','src':cImage});
                }

                if (o.canSelect) {
                    a = new Element('a', { 'styles': { 'text-decoration': 'underline'} });

                    // add tip
                    if (col.tipTitle) {
                        tip = self._getData(item, col.tipTitle);
                        if (tip) {
                            a.store('tip:title', tip);
                            a.set('class', 'Tips');
                        }
                    }
                    if (col.tipText) {
                        tip = self._getData(item, col.tipText);
                        if (tip) {
                            a.store('tip:text', tip);
                            a.set('class', 'Tips');
                        }
                    }

                    // add navigational link
                    if (col.URL) {
                        if (col.Target) {
                            var tgt = self._getData(item, col.target);
                            if (tgt) { a.target = tgt; }
                        }
                        if (col.urlCssClass) {
                            var cls = self._getData(item, col.Target, col.urlCssClass);
                            if (cls) { a.set('class', tgt); }
                        }

                        var url = self._getData(item, col.Target, col.urlCssClass);
                        if (url) {
                            url = url.replace(/~/, o.navigateURL);
                            a.set('href', url);
                        }
                    } else a.setStyle('text-decoration', 'none');

                    // add image
                    if (img) {
                        a.setStyle('text-decoration', 'none');
                        a.appendChild(img);
                        var s = new Element('a', { 'styles': { 'text-decoration': 'underline'} }).inject(a);
                        //s.appendChild(txt);
                        s.set("html",txt);
                    } else {
                    	//a.appendChild(txt);
                    	a.set("html",txt);
                    }
					if (!o.showCheckBox || i != 0) {td.appendChild(a);}
                    

                    // create tip object
                    if (col.tipTitle) var tip = new Tips(new Array(a), { maxTitleChars: 50 });
                } else { if (img) td.appendChild(img); td.appendChild(txt); }
            } else {
                // add columns
                if(col.type == "checkbox") {
                    var chk=new Element('input', { 'type': 'checkbox', 'name': id + '_' + col.name, id:id + '_' + col.name + i ,'value':value }).inject(td);
                    if((''+self._getData(item, col.name))=='true') chk.set('checked','true');
                } else {
                	//td.appendChild(txt);
                	td.set('html',txt);
                }
            }
            self.fireEvent('itemColumnBound', [item,self,col,td] );
        }

        var cm=o.commands;
        if (cm && cm.length > 0 && o.showCommand) {
            tid = rid + '_commands';

            // create command cell
            td = tr.getElementById(tid);
            if (td) td.empty();
            else { td = new Element('td', { 'id': tid }); tr.appendChild(td); }

            for (i = 0; i < cm.length; i++) {
                var cmd = cm[i];

                // show event is used to determine if commands should be displayed
                var showEvt = self.canShowEvent(self,item,cmd.name);
                if (showEvt) {
                    a = $(new Element('a'));
                    a.title = cmd.text;
                    a.href = "#" + cmd.name;
                    a.addEvent('click', function(e) { self.onItemCommand(e,item,parent,cmd); return false; });

                    td.appendChild(a);

                    if(cmd.image) {
                        img = new Element('img');
                        img.alt = cmd.text;
                        img.src = o.iconPath + cmd.image;
                        a.appendChild(img);
                    } else {
                        a.set('html',cmd.text);
                    }
                }
            }
        }

        // add select events
        if (o.canSelect) {
            tr.removeEvents('mouseover');
            tr.removeEvents('mouseout');
            tr.removeEvents('click');
            tr.addEvent('mouseover', function(e) { self.onItemOver(e,item,parent); });
            tr.addEvent('mouseout', function(e) { self.onItemOut(e,item,parent); });
            tr.addEvent('click', function(e) { self.onItemClick(e,item,parent); });
        }

        return tr;
    },


    
    autoCheck: function(){
    	//alert('curCheckIds.length='+curCheckIds.length);
    	var self = this;
    	var o = self.options;
    	var m = document.getElementsByName(o.cbName); 
   	 	var l = m.length;
        for ( var i=0; i< l; i++)
        {
        	if(null!=o.curCheckIds && o.curCheckIds.length>0){
        		if ( o.saveCheck && o.curCheckIds.contains(m[i].value) )
        		{
        			m[i].checked = true ;
        		}
        	}
        }
    },
    
    _getData: function(item,property){
        if(!item || !property) return '';
        if(item[property]==null) return '';
        return item[property]; 
    },

    onItemCommand: function(e,item,parent,cmd) {
        var self = this;
        e = new Event(e);
        e.stop();
        var t = $(e.target);
        if (t.nodeName != 'A') t = t.getParent('a');
        var img = t.getElement('img');
        self.fireEvent('itemCommand', [item,self,cmd,img]);
    },

    onItemClick: function(e,item,parent) {//点击行(选中行)
        var self = this;
        var o=self.options;

        // set last selected for entire control
        o.value = item.value;
        o.selectedItem = item;

        self.fireEvent('itemSelected', [item,self,parent]);
        /*
        if (item._element || parent) {
            if(!parent) parent=item._element.getParent();
            parent.getElements('.C').removeClass('C');
            item._element.addClass('C');
        }
        */
        if (item._element) {
            parent.getElements('.C').removeClass('C');
            item._element.addClass('C');
        }
        return this;
    },

    onItemOver: function(e,item) {//鼠标移到行上
        if (item._element) { item._element.addClass('O'); }
        return this;
    },

    onItemOut: function(e,item) {//鼠标离开行
        if (item._element) { item._element.removeClass('O'); }
        return this;
    },    

    canShowEvent: function() { return true; },

    update: function(items)
    {
        var self=this;
        self.options.items = items;
        self.toDOM();
    },
    
    findCurrentPage: function(){
    	var self = this;
        var o=self.options;
        //var pageno=1;
        //if (o.pageCurrentPage > 0) { pageno = o.pageCurrentPage; }
        //alert(o.pageCurrentPage);
    	return o.pageCurrentPage;
    },
    
    goPage: function(pageno){
    	var self = this;
        var o=self.options;
        o.pageCurrentPage = pageno;
    },
    
    //ajax方式取数据
    findList: function(pageno,cancelCheck)
    {
    	var self=this;
    	var o = self.options;
    	o.pageCurrentPage = pageno;
    	//alert(o.pageCurrentPage);
    	var pageurl = o.dataURL;
    	var params = o.dataURLParams;
    	if(params.condition) 
    	alert('in list.js list --'+params.condition);
    	params.pageno = pageno;
    	params.timestamp= new Date().getTime();
    	//alert(params.timestamp);
		var request = new Request.JSON({
			url: pageurl,
			onComplete: function(json,text) {
				o.items = json.recorders;
				o.pageOverView = json.overview;
				if ($(o.container)){
					$(o.container).innerHTML = '<img src = "'+MUI.themePath()+'images/spinner.gif">';				
				}	
				self.toDOM();
				self.autoCheck();
				if(cancelCheck){
					self.cancelAll();
					self.clearCheckIds();
				}
			}//onComplete
		}).get(params);//Request.JSON
    }
});

